##################
# Replication Files for Figure 2
##################
setwd("/users/irismalone/Dropbox/AGDPapers/IS-ISSS Paper/Replication Files - II/Data")
require(ggplot2)
require(ggpubr)

require(ggplot2)
suppressMessages(require(maps))
suppressWarnings(suppressMessages(require(ggmap)))
suppressMessages(require(mapproj))
suppressMessages(require(countrycode))
suppressWarnings(suppressMessages(require(dplyr)))

#################
# Figure 2 Creation

# Figure 2A: Time Series Plot

df = read.csv("time-series-data.csv")

df$nonrebel = df$noact2 - df$noinsurg
pdf("noact_fragment.pdf", 10, 8)
ggplot(data=df)  + geom_line(aes(x=year, y=noact2, colour="All"), lwd=3) + geom_smooth(aes(x=year, y=noact2)) + geom_line(aes(x=year, y=nonrebel, colour="Non-Rebel"), lwd=3) + geom_smooth(aes(x=year, y=nonrebel)) + 
  geom_line(aes(x=year, y=noinsurg, colour="Rebel"), lwd=3) + geom_smooth(aes(x=year, y=noinsurg)) + theme_bw() + 
  xlab("Year") + ylab("Number of Active Armed Groups")  + 
  guides(colour=guide_legend(title="Type of Group:")) + theme(text = element_text(size=25)) +  
  theme(legend.position='top') + scale_color_manual(values=c("darkred", "blue", "orange"))
dev.off()


# Figure 2B: Global Map

df = read.csv("cross-sectional-data.csv")

world = map_data("world")
df$cown = df$ccode
dfname = with(codelist, data.frame(cown, country.name.en))
df3 = merge(df, dfname,id="cown", all=T)
df3$country.name.en[df3$country.name.en=="Côte d’Ivoire"] = "Ivory Coast"

df3$region = df3$country.name.en
world$region[world$region == "Yemen"] = "Yemen Arab Republic"
world$region[world$region == "USA"] = "United States"
world$region[world$region == "Russia"] = "Russia"
world$region[world$region == "Venezuela, Bolivarian Republic of"] =  "Venezuela" 
world$region[world$region == "UK"] = "United Kingdom"
world$region[world$region == "Democratic Republic of the Congo"] = "Congo - Kinshasa"
world$region[world$region == "Republic of Congo"] = "Congo - Brazzaville"
world$region[world$region == "Serbia"] = "The former Yugoslav Republic of Macedonia"
world$region[world$region == "Republic of Vietnam"] = "Vietnam"
world$region[world$region == "Korea, Republic of"] = "South Korea"
world$region[world$region == "Korea, Democratic People's Republic of"] = "North Korea"
world$region[world$region == "Syrian Arab Republic"] = "Syria"
world$region[world$region == "Tanzania, United Republic of"] = "Tanzania"
world$region[world$region == "Bolivia, Plurinational State of"] = "Bolivia"
world$region[world$region == "Iran (Islamic Republic of)"] = "Iran"
#world$region[world$region == "Ivory Coast"] = "Côte D'Ivoire"
world$region[world$region == "Lao People's Democratic Republic"] =  "Laos" 
world$region[world$region == "Turkmenistan"] = "Turkmenistan"
world$region[world$region == "Palestine, State of"] = "Israel"
world$region[world$region == "United Kingdom of Great Britain and Northern Ireland "] = "United Kingdom"
world$region[world$region == "Yugoslavia"] = "The former Yugoslav Republic of Macedonia"
world$region[world$region == "Myanmar"] = "Myanmar (Burma)"
world$region[world$region == "Myanmar"] = "Myanmar (Burma)"
world$region[world$region == "USA"] = "United States"

df3$lnact = log(df3$noact+1)
df3$noact[is.na(df3$noact)==TRUE] = 0
df3$lnact[is.na(df3$lnact)==TRUE] = 0

require(viridis)

g = ggplot()
g = g + geom_map(data=world, map=world,
                 aes(x=long, y=lat, map_id=region),
                 fill="#ffffff", color="#ffffff", size=0.15)
g= g + geom_map(data=df3, map=world,
                aes(fill=lnact, map_id=region),
                color="#ffffff", size=0.15) +
  coord_cartesian(ylim = c(-50, 80)) + scale_fill_viridis(direction=-1,  guide='colorbar', name = "Ln(Number Armed Groups)") +  xlab("Latitude") + ylab("Longitude")   + theme(plot.title = element_text(hjust = 0.5), legend.position="bottom", legend.key.width =unit(1.5,"cm")) +  theme(text = element_text(size=25)) +  theme(text = element_text(size=25))
g


ggsave("fullmap.png", g, width=20, height=14)
g


df3$noact[is.na(df3$noact)==TRUE] = 0

#############
# Figure 3: Frequency of Support
#############

#bar chart of support
df=read.csv("replication_extsup_data.csv")
df = df %>% distinct(ccode1, ccode2, torgid, .keep_all = TRUE)

length(unique(df$torgid))
length(unique(df$torgid[df$anystatesup==1]))
length(unique(df$torgid[df$civwar==1]))
length(unique(df$ccode))
length(unique(df$ccode2[df$anystatesup==1]))

require(stargazer)
df$sharedcoideo = df$leftideational+df$sharedrelig+df$sharedethnicpower
df$sharedcoideo[df$sharedcoideo >0] = 1

df2 = subset(df, df$torgid!=28 & df$polopp==1)#remove Al Qaeda outlier and subset to polopp

dfsummstats = with(df2, data.frame(anystatesup, sharedcoideo, sharedethnicpower, sharedcoideo2, leftideational, sharedrelig, shiaideational, sunniideational))
stargazer(dfsummstats, median = T, omit.summary.stat = c("p25", "p75"))

library(gapminder)
library(tidyverse)
df_distinct = df %>%
  filter(anystatesup==1)  %>% 
  select(torgid, anystatesup, statetypesupmaterial, statetypesuptrain, 
                          statetypesupfinancial, statetypesupterr, 
                          statetypesupendorse, statetypesupother) %>% 
  distinct(.keep_all= TRUE)


summ_bar = df_distinct %>% 
  summarise(
          #Total = sum(statesup==1, na.rm = T),
           Material = sum(statetypesupmaterial==1, na.rm = T),
           Training = sum(statetypesuptrain==1, na.rm = T),
           Financing = sum(statetypesupfinancial==1, na.rm = T),
         Sanctuary = sum(statetypesupterr==1, na.rm = T),
           Endorsement = sum(statetypesupendorse==1, na.rm = T),
           Logistical = sum(statetypesupother==1, na.rm=T)) %>% 
  gather( "category", "counts")

pdf("typesstatesup.pdf", 12, 5)
ggplot(summ_bar, aes(x=fct_reorder(category, -counts), counts), colour=factor(category)) + 
  geom_col(position = "dodge") + geom_text(aes(label=counts), position=position_dodge(width=0.9), vjust=-0.3) + theme_bw() + ylab("Frequency") + xlab("Type of External Support")
dev.off()

###################
## Figure 4: Total Number
###################

df = read.csv("extsup_countrytrends.csv")
df = subset(df, is.na(df$sponsorstate)==FALSE)
df$sponsorstate = as.numeric(df$sponsorstate)


df$sponsor_country_txt <- countrycode(df$sponsorstate, "cown", "country.name.en")


#conditional on sponsoring more than 1
df = subset(df, df$sponsor_totalgroups > 1)
df$sponsor_totalgroups = as.numeric(df$sponsor_totalgroups)
df = with(df, data.frame(sponsor_country_txt, sponsor_totalgroups))
df = df[!duplicated(df), ]

pdf("sponsor_totalgroups.pdf", 12, 8)
ggplot(df,  aes(x = reorder(sponsor_country_txt, -sponsor_totalgroups), y = sponsor_totalgroups)) + geom_bar(stat = "identity", fill="blue") + theme_classic() + theme(axis.text.x = element_text(angle = 45, hjust=1)) 
 dev.off()
 
pdf("sponsor_totalgroups.pdf", 12, 8)
ggbarplot(df, x = "sponsor_country_txt", y = "sponsor_totalgroups",
          fill="blue",
          color = "white",            # Set bar border colors to white
          palette = "jco",            
          sort.by.groups = FALSE,     # Don't sort inside each group
          x.text.angle = 85,           # Rotate vertically x axis texts
          sort.val = "desc"          # Sort the value in descending order
)
dev.off()
